import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit

def test6():
    """已经实现了从鼠标点 然后正弦曲线下移的动态操作"""
    fig, ax = plt.subplots()
    x = np.array([-5,-4,-3,-2,-1,0, 1,2,3,4,5]).astype(np.float64)
    print(type(x),x,x.shape,x[0])
    y = np.square(x).astype(np.float64)
    print(type(y), y, y.shape,y.dtype,y[0])
    #line = ax.plot(x, y)[0]
    plt.ylim(-5, 35)
    ax.scatter(x,y)
    mouseXY=[]

    # 忽略除以0的报错
    np.seterr(divide='ignore', invalid='ignore')

    # 二阶曲线方程
    def func_2(x, a, b, c):
        return a * np.power(x, 2) + b * x + c

    def on_key_press(event):
        fig.canvas.mpl_connect('motion_notify_event', on_key_move)  # 鼠标点击事件

    def on_key_move(event,y=y):
        x_mouse, y_mouse= event.xdata, event.ydata

        ind=[]
        #计算一下鼠标的位置和点的位置只差
        for i in range(len(x)):
            #计算一下举例
            d = np.sqrt((x_mouse -x[i] ) ** 2 + (y_mouse -y[i]) ** 2)
            if d<0.8:
                print("i:",i,"\tx[i]:",x[i],'\ty[i]:',y[i],'\td:',d)
                ind.append(i)

        mouseXY.append([x_mouse, y_mouse])
        print(len(mouseXY),"数组的长度:",len(mouseXY))
        if ind:
            if len(mouseXY)>=2 and mouseXY[-1][-1]-mouseXY[-2][-1]>0:
                print("ind[0]:",ind[0])
                print("x,y之前:",x,y)
                y[ind[0]] = y_mouse
                x[ind[0]] = x_mouse
                print("x,y之后:",x,y)

                popt2, pcov2 = curve_fit(func_2, x, y)
                a2 = popt2[0]
                b2 = popt2[1]
                c2 = popt2[2]

                yvals2 = func_2(x, a2, b2, c2)

                ax.cla()
                plt.ylim(-5, 35)
                ax.scatter(x, y)
                ax.plot(x, yvals2)
                fig.canvas.draw_idle()  # 重新绘制整个图表，
            else:
                print("ind[0]:",ind[0])
                print("x,y之前:",x,y)
                print(x_mouse,y_mouse)
                y[ind[0]] = y_mouse
                x[ind[0]] = x_mouse
                print("x,y之后:",x,y)
                popt2, pcov2 = curve_fit(func_2, x, y)
                a2 = popt2[0]
                b2 = popt2[1]
                c2 = popt2[2]

                yvals2 = func_2(x, a2, b2, c2)

                ax.cla()
                plt.ylim(-5, 35)
                ax.scatter(x, y)
                ax.plot(x, yvals2)
                fig.canvas.draw_idle()  # 重新绘制整个图表，
            fig.canvas.draw_idle()  # 重新绘制整个图表，

    def on_key_release(event):
        fig.canvas.mpl_disconnect( fig.canvas.mpl_connect('motion_notify_event', on_key_move))  # 鼠标点击事件


    fig.canvas.mpl_disconnect(fig.canvas.manager.key_press_handler_id)  # 取消默认快捷键的注册
    fig.canvas.mpl_connect('button_press_event', on_key_press)#鼠标点击事件
    fig.canvas.mpl_connect('button_release_event', on_key_release)#鼠标松开
    plt.show()

test6()